package pattern.mq.consumer;

import com.baomidou.mybatisplus.core.toolkit.SerializationUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import pattern.WorkServiceTool;
import pattern.cache.InitCache;
import pattern.dto.SysLog;
import pattern.enums.mq.SubscribeTopicEnum;
import pattern.mq.AbstractConsumerSubscribe;

import java.util.List;
import java.util.Objects;

/**
 * 系统日志记录 消费处理
 * @author Simon
 * */
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SysLogMqConsumer extends AbstractConsumerSubscribe implements ApplicationRunner {
    private final InitCache initCache;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //初始化
        super.init();
    }

    @Override
    protected SubscribeTopicEnum getSubscribeTopicEnum() {
        return SubscribeTopicEnum.SYS_LOG_TOPIC;
    }

    @Override
    protected InitCache getInitCache() {
        return initCache;
    }


    @Override
    protected void consume(MessageExt msg, ConsumeConcurrentlyContext context) {
        SysLog sysLog = (SysLog) SerializationUtils.deserialize(msg.getBody());
        if (Objects.isNull(sysLog)) {
            log.error("日志消费异常：{}", msg);
            return;
        }
        WorkServiceTool.getSysLogService().save(sysLog);
    }

    @Override
    protected void exception(List<MessageExt> msg, ConsumeConcurrentlyContext context) {
        log.error("日志消费异常");
    }
}
